﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evpo.ContactData.ViewModel;
using Evpo.ContactData.Common;
using System.IO;
using Evpo.ContactData.UI.GeneralClasses;

namespace Evpo.ContactData.UI
{
    public partial class ExportForm : System.Web.UI.Page
    {
        #region Properties
        protected ExportViewModel Model
        {
            get;
            set;
        }

        #endregion Properties

        #region Handlers
        protected void Page_Init(object sender, EventArgs e)
        {
            Model = new ExportViewModel((IConnection)Session[SessionStateKeys.Connection]);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                uiDownload.DataBind();
            }
        }

        protected void uiDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters["model"] = Model;
        }

        protected void uiListBox_DataBound(object sender, EventArgs e)
        {
            if (uiListBox.Items.Count > 0)
            {
                uiListBox.SelectedIndex = 0;
            }
        }

        protected void uiDownload_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader(
                "Content-Disposition",
                String.Format("attachment; filename=\"{0}\"", uiListBox.SelectedItem.Text + ".xml")
                );

            byte[] buffer = new byte[Preferences.BufferSize];

            using (Stream stm = new MemoryStream())
            {
                Model.GenerateExport(int.Parse(uiListBox.SelectedValue), stm);

                int readBytes = stm.Read(buffer, 0, buffer.Length);
                while (readBytes > 0 && Response.IsClientConnected)
                {
                    Response.OutputStream.Write(buffer, 0, readBytes);
                    Response.Flush();
                    readBytes = stm.Read(buffer, 0, buffer.Length);
                }

                stm.Close();
            }

            Response.OutputStream.Close();
            Response.Close();
        }

        #endregion Handlers



    }
}